﻿using System;
using Microsoft.SharePoint;
using PS.Practices.Provisioner.Provisioner.Util;
using PS.Practices.Provisioner.Sandbox.Util;

namespace PS.Practices.Provisioner.Sandbox.ProvisionerEventReceiver
{
    /// <summary>
    /// Web Events
    /// </summary>
    public class ProvisionerEventReceiver : SPWebEventReceiver
    {
       /// <summary>
       /// A site was provisioned.
       /// </summary>
       public override void WebProvisioned(SPWebEventProperties properties)
       {
           SPWeb spWeb = properties.Web;
           var script = GetScript(spWeb);
           var interpreter = new SiteBuilder.Features.Schema.Interpreter();
           using (var logger = new SandboxProvisionerLogger(spWeb))
           {
               interpreter.ProcessScriptSandboxed(spWeb, script, logger);
           }
       }

       private static string GetScript(SPWeb spWeb)
       {
            var associatedTemplate = String.Format("{0}#{1}", spWeb.WebTemplate, spWeb.Configuration);
           
            var rootWeb = spWeb.Site.RootWeb;
            
            var provScriptList = rootWeb.Lists["Provisioner Scripts"];

            var query = new SPQuery
                            {

                                Query =
                                    String.Format(
                                        "<Where><Eq><FieldRef Name='Templates'/><Value Type='Text'>{0}</Value></Eq></Where>",
                                        associatedTemplate),
                                RowLimit = Constants.SpQueryRowLimit
                            };

            SPListItemCollection myItems = provScriptList.GetItems(query);

            if (myItems.Count > 0)
            {
                return (string) myItems[0]["Script"];
            }
            return null;
        }
    }
}
